/**
 * Created by user on 17/2/15.
 */
let config = require( '../config'),
    ServiceRequest = require('../lib/ServiceRequest'),
    monitor = require('@futu/monitor'),
    {getLogger} = require('../utils');

module.exports = exports.default = {
    loginByCookie: async function(ctx) {
        let uid = ctx.cookies.get('uid'),
            web_sig = ctx.cookies.get('web_sig');

        if (isNaN(uid) || web_sig === undefined || web_sig.length === 0) {
            return false;
        }
        web_sig = decodeURIComponent(web_sig);

    //console.log(`uid:${uid}, websig:${web_sig}`);
        let realIp = ctx.getRealIp();
        let start = new Date;
        let request = new ServiceRequest(config.endpoints.common_support, config.isDevEnv ? 1 : 0);
        let responseBody = await request.header({
            'x-futu-client-nnid': uid,
            'x-futu-client-websig': web_sig,
            'x-futu-client-lang': 'sc',
            'x-futu-client-domain': config.app.domain,
            'x-futu-client-ip': realIp
        }).get('/user');
        const ms1 = new Date - start;
    //console.log(`loginByCookie ${ctx.method} ${ctx.url} - ${ms1}ms`);

        let {result, message, data} = responseBody;
        if(result === 0){
            ctx.authUser.setUser(Object.assign(data, {uid, web_sig}));
        } else {
            if (result === 11) {
        //sig鉴权失败
                monitor.report(1);
                let logger = getLogger(1, 0, uid, realIp);
                logger.error(`loginByCookie ${ctx.method} ${ctx.url} - websig validate failed. web_sig:${web_sig}`);
            }
            console.error(responseBody);
        }
    }
};
